package com.groot.system.service;

import java.util.ArrayList;
import java.util.List;

import javax.transaction.Transactional;

import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.groot.common.repository.dbutil.QueryHelper;
import com.groot.common.service.BaseService;
import com.groot.common.web.pager.PagerVo;
import com.groot.system.entity.Menu;

@Service
@Transactional
public class MenuService extends BaseService<Menu> implements IMenuService {

	@Override
	public Menu add(Menu entity) {
		return this.hibernate.add(entity);
	}

	@Override
	public void delete(int id) {
		this.hibernate.delete(Menu.class, id);
	}

	@Override
	public void update(Menu entity) {
		this.hibernate.update(entity);
	}

	@Override
	public Menu get(int id) {
		return null;
	}

	
	@Override
	@Cacheable(value="serviceCache", key="#root.methodName")
	public List<Menu> list(Menu entity) {
		String sql = "SELECT  t.id, t.name, t.datetime FROM groot_sys_menu t WHERE 1=1";
		List<Object> params = new ArrayList<Object>();
		sql = addWhere(sql, entity, params);
		return QueryHelper.query(Menu.class, sql, params.toArray());
	}

	@Override
	//@Cacheable(value="serviceCache", key="#root.methodName")
	public PagerVo<Menu> pager(Menu entity) {
		PagerVo<Menu> page = new PagerVo<Menu>() ;
		page.setDataRows(find(entity)) ;
		page.setTotal(QueryHelper.stat("SELECT COUNT(t.id) FROM groot_sys_menu t", new Object[]{})) ;
		return page;
	}
	
	public List<Menu> find(Menu entity) {
		String sql = "SELECT  t.id, t.name, t.datetime FROM groot_sys_menu t WHERE 1=1";
		List<Object> params = new ArrayList<Object>();
		sql = addWhere(sql, entity, params);
		return QueryHelper.query_slice(Menu.class, sql, params.toArray()) ;
	}

	private String addWhere(String sql, Menu entity, List<Object> params) {
		if (null != entity) {
			if (null != entity.getId()) {
				sql += " AND id=?";
				params.add(entity.getId());
			}
		}
		return sql;
	}

}
